IF EXISTS (SELECT *
           FROM INFORMATION_SCHEMA.ROUTINES
           WHERE ROUTINE_NAME='pAddReturnProductDetailWithBill'
           AND ROUTINE_SCHEMA='dbo'
           AND ROUTINE_TYPE='PROCEDURE'
          )
          DROP PROCEDURE dbo.pAddReturnProductDetailWithBill
GO

CREATE PROC dbo.pAddReturnProductDetailWithBill
  @vintReturnProductId     INT,
  @vintBillDetailId        INT,
  @vintAmount			   INT,
  @vbitSuccess			   BIT OUTPUT
AS
/*@@*_____________________________________________________________________

  

_____________________________________________________________________*@@*/

/*______________________ CONSTANT DECLARATIONS _________________________*/

  DECLARE
    @cstrThisProc              NVARCHAR(128),
    @cintErrGeneral            INT

  SET @cstrThisProc            = N'pAddReturnProductDetailWithBill'
  SET @cintErrGeneral          = 50000  -- General error. Used when an
                                        -- error has occurred and no other
                                        -- specific error condition is
                                        -- assigned.

/*______________________ VARIABLE DECLARATIONS _________________________*/

  DECLARE
    @intErrNo       INT,
    @strErrMsg      NVARCHAR(400),
    @intReturn      INT

/*_______________________________ INIT _________________________________*/

  -- Setting NOCOUNT ON prevents additional recordsets with the
  -- "number of records affected" from being returned, which is not
  -- handled the same by all providers, such as for OLEDB vs. ODBC.
  SET NOCOUNT ON

/*________________________ VALIDATE PARAMETERS _________________________*/
	DECLARE @intInProdDetailId INT
	DECLARE @intBillDetail_InProdDetailAmount INT
	DECLARE @intBillDetail_InProdDetailId INT

	
	DECLARE @intSalePrice		   INT
	DECLARE @intProductId		   INT
	DECLARE @datSaleTime		   DATETIME
	DECLARE @intBillId			   INT

/*_______________________________ MAIN _________________________________*/
	
	
	BEGIN TRANSACTION
	BEGIN TRY
	
	SELECT @intSalePrice = SalePrice,
		@intProductId = ProductId,
		@intBillId = BillId
	FROM BillDetail
	WHERE Id = @vintBillDetailId
	
	SELECT @datSaleTime = SaleTime
	FROM Bill
	WHERE Id = @intBillId
		
	INSERT INTO ReturnProductDetail (
		Amount,
		ReturnProductId,
		ProductId,
		SalePrice,
		SaleTime,
		BillDetailId
	) VALUES ( 
		@vintAmount,
		@vintReturnProductId,
		@intProductId,
		@intSalePrice,
		@datSaleTime,
		@vintBillDetailId
	)

	-- Increase product amount
	UPDATE Product
	SET Product.Amount = Product.Amount + @vintAmount
	FROM Product
	WHERE Product.Id = @intProductId
	
	-- Update amount of bill detail
	UPDATE BillDetail
	SET Amount = Amount - @vintAmount
	WHERE BillDetail.Id = @vintBillDetailId
	
	-- Increase InProdDetail (bottom up) and delete BillDetail_InProdDetail if return amount >= it's amount
	WHILE @vintAmount > 0
	BEGIN
		SET @intBillDetail_InProdDetailId = NULL
		SET @intBillDetail_InProdDetailAmount = NULL
		SET @intInProdDetailId = NULL
		
		SELECT TOP 1
			@intBillDetail_InProdDetailId = Id,
			@intBillDetail_InProdDetailAmount = Amount,
			@intInProdDetailId = InProdDetailId
		FROM BillDetail_InProdDetail
		WHERE BillDetailId = @vintBillDetailId
		ORDER BY Id DESC -- Buttom Up
		
		IF @intBillDetail_InProdDetailId IS NOT NULL BEGIN
			-- Update in prod detail
			UPDATE InOutProdDetail
			SET RemainAmount = CASE
								 WHEN @vintAmount > @intBillDetail_InProdDetailAmount THEN ISNULL(RemainAmount, 0) + @intBillDetail_InProdDetailAmount
								 ELSE ISNULL(RemainAmount, 0) + @vintAmount
							   END
			WHERE InOutProdDetail.Id = @intInProdDetailId
			
			-- Delete BillDetail_InProdDetail if return amount >= it's amount
			IF @vintAmount >= @intBillDetail_InProdDetailAmount BEGIN
				DELETE FROM BillDetail_InProdDetail
				WHERE Id = @intBillDetail_InProdDetailId
			END
			ELSE BEGIN -- Update Amount of BillDetail_InProdDetail if it's amount > return amount
				UPDATE BillDetail_InProdDetail
				SET Amount = Amount - @vintAmount
				WHERE Id = @intBillDetail_InProdDetailId
			END
			
			SET @vintAmount = @vintAmount - @intBillDetail_InProdDetailAmount
		END
		ELSE BEGIN
			SET @vintAmount = 0 -- break while
		END
	END -- END WHILE
	
	-- Return value 1 indicates success
	SET @vbitSuccess = 1
	
	END TRY
	BEGIN CATCH
		GOTO lblError
	END CATCH

	IF @@TRANCOUNT > 0 BEGIN
		COMMIT TRANSACTION
	END
	RETURN
/*___________________________ ERROR HANDLER ____________________________*/
lblError:
  -- An error has occurred.  On entering this section @intErrNo should
  -- already hold the error number
	
	IF @@TRANCOUNT > 0 BEGIN
		ROLLBACK TRANSACTION
	END
	
	SET @vbitSuccess = 0
	
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	
	SELECT 
		@ErrorMessage = ERROR_MESSAGE(),
		@ErrorSeverity = ERROR_SEVERITY(),
		@ErrorState = ERROR_STATE();

	-- Use RAISERROR inside the CATCH block to return error
	-- information about the original error that caused
	-- execution to jump to the CATCH block.
	RAISERROR (@ErrorMessage, -- Message text.
			   @ErrorSeverity, -- Severity.
			   1 -- State.
			   );